import { useRoutes } from "react-router-dom";
import routes from "./router";
import { App as AntdAppp } from "antd";
import { useEffect, useMemo } from "react";
import { useAtomValue } from "jotai";
import { userAtom } from "./store/indext";

function App() {
  const user = useAtomValue(userAtom);
  useEffect(() => {
    const token: string | null = localStorage.getItem("token") || null;
    const isWhite = ["/sgks_teacher/login"].includes(location.pathname);
    if (!token) {
      if (isWhite) return;
      location.replace("/sgks_teacher/login");
    } else {
      if (isWhite) {
        location.replace("/sgks_teacher/");
      }
    }
  }, []);

  // 新增：根据角色过滤 routes
  const filteredRoutes:any = useMemo(() => {
    if (user.roleCodes?.includes("ROLE_ADMIN")) {
      return routes;
    }
    // 过滤掉 path 为 "user" 的菜单
    return routes.map(route => {
      if (route.path === "/") {
        return {
          ...route,
          children: route.children?.filter(child => child.path !== "user"),
        };
      }
      return route;
    });
  }, [user.roleCodes]);

  const RouterPage = useRoutes(filteredRoutes);

  return <AntdAppp className="h-[100vh]">{RouterPage}</AntdAppp>;
}

export default App;
